/*
 * 
 */
package kds.network.http;

import java.util.ArrayList;

import android.util.Log;

/**
 * The Class URLSyncManager is class manager thread like
 * HTTPRequestLoaderManager Request push to this queue cann't cancel ad alive
 * util application end
 * 
 */
public class URLSyncManager {

	/** The request sync manager. */
	private static URLSyncManager requestSyncManager;

	/** The queue. */
	private ArrayList<Runnable> queue = new ArrayList<Runnable>();

	/** The active. */
	private ArrayList<Runnable> active = new ArrayList<Runnable>();

	/**
	 * Instantiates a new uRL sync manager.
	 */
	private URLSyncManager() {
		Log.i("URLSyncManager",
				"Create new instace URLSycnRequest sync manager");
	}

	/**
	 * Gets the sync queue.
	 * 
	 * @return the sync queue
	 */
	public static URLSyncManager getSyncQueue() {
		if (requestSyncManager == null)
			requestSyncManager = new URLSyncManager();
		return requestSyncManager;
	}

	/**
	 * Push.
	 * 
	 * @param runnable
	 *            the runnable
	 */
	public void push(Runnable runnable) {
		Log.i("URLSyncManager", "Have one request push to SYNC QUEUE");
		queue.add(runnable);
		if (active.size() < 1)
			startNextRequest();

	}

	/**
	 * Start next request.
	 */
	public synchronized void startNextRequest() {
		if (!queue.isEmpty()) {
			Runnable next = queue.get(0);
			queue.remove(0);
			active.add(next);
			Thread thread = new Thread(next);
			thread.start();
		}
	}

	/**
	 * Did request loader.
	 * 
	 * @param runable
	 *            the runnable
	 */
	public synchronized void didRequestLoader(Runnable runable) {
		Log.i("URLSyncManager",
				"Have one request did finish load from SYNC QUEUE");
		active.remove(runable);
		startNextRequest();
	}

}
